<template>
  <div class="order-submit-box ">
    <div class="order-notice-box" v-if="voucherStatus">
      <p class="knife_container">{{activeNotice}}</p>
    </div>
    <div class="knife_container">
      <div class="orderInfoBox">
        <!-- 收货信息 -->
        <ReceveInformation @getAddrId="getAddrId" @getWareId="getWareId" @modifReceive="modifReceiveAddr"/>
        <!-- 商品信息 -->
        <goodsInfo :orderInfosList="orderInfosList" :nowDiscount="userDiscount"></goodsInfo>
        <!-- 选择赠品 -->
        <!-- <div class="order-invoice" style="padding-bottom: 0;margin-top:30px;" v-if="giftChooseNum > 0">
          <GiftList :giftList="giftList" :activityId="activityId" :giftChooseNum="giftChooseNum" v-if="giftChooseNum > 0" @selectedGiftFun='getSelectedGiftFun'></GiftList>
        </div> -->
        <!-- 开票 -->
        <div class="order_deliver_box">
          <span class="info_title"><i class="el-icon-star-on color-red pad-right8"></i>
            交易类型
            <el-tooltip class="item" effect="dark" content="电子普通发票与纸质发票具有同等法律效力，可支持报销入账、商品售后凭证。" placement="right">
              <span class="el-icon-info"></span>
            </el-tooltip>
          </span>
          <section class="order_detail">
            <el-radio-group v-model="neededInvoice">
              <el-radio :label="false" class="order_font">平台交易</el-radio>
              <el-radio :label="true" class="order_font">自营销售(含税)</el-radio>
            </el-radio-group>
            <!-- <el-checkbox v-model="neededInvoice"><span class="order_font">开票</span></el-checkbox> -->
            <transition name="el-fade-in-linear">
              <div class="invoice_box" v-if="neededInvoice">
                <div v-show="invoiceList.length > 0" class="invoice_input">
                  <span class="order_deliver_title">发票信息 :</span>
                  <el-select v-model="invoiceId" placeholder="请选择" class="order_select" @change="selectInvo">
                    <el-option v-for="item in invoiceList" :key="item.id" :label="item.type === 1 ? '单位 - ' + item.title : '个人 - ' + item.title" :value="item.id"></el-option>
                  </el-select>
                </div>
                <span class="notice_text" @click="openNewInvo">新增</span>
              </div>
            </transition>
          </section>
        </div>
        <!-- 分仓发货 -->
        <section class="order_deliver_box">
          <span class="info_title"><i class="el-icon-star-on color-red pad-right8"></i>发货仓</span>
          <section class="order_detail">
            <el-radio-group v-model="selectWarehouseVal">
              <template v-for="(item, index) in usableWareList">
                <el-radio :label="item.id" class="order_font" :key="index">{{item.name}}仓</el-radio>
              </template>
            </el-radio-group>
            <p v-if="selectWarehouseVal !== 1" class="warenotice">已根据您的配送地址,自动为您选择较近的{{warehouseName[0]['name']}}仓发货</p>
          </section>
        </section>
        <div class="order_deliver_box">
          <p class="info_title">配送 <span class="reward" v-show="levelInfoObj.freightReduction">可抵扣快递首重运费</span></p>
          <div>
            <span class="order_deliver_title">配送方式 :</span>
            <el-select v-model="resultDeliver" placeholder="请选择" class="order_select" @change="fetchPostage" style=" width: 150px;">
              <el-option v-for="item in transportlist" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
            <span class="order_deliver_title">商品总重 :</span>
            <span class="order_deliver_content">{{totalWeight > 1000 ? totalWeight /1000 : totalWeight | floatPrices}}{{totalWeight > 1000 ? '千克' :'克'}}</span>
          </div>
        </div>
        <!-- 优惠信息 v-if="activityId === 0"  -->
        <order-voucher
            :resultDeliver="resultDeliver === '' ? 0 : resultDeliver"
            :brandawardArr="brandawardArr" 
            :ordinaryMoney="ordinaryMoney"
            :isShowFriAndRed="isShowFriAndRed"
            :activePro="activePro"
            :discount="userDiscount"
            :ordinaryPro="ordinaryPro"
            @selectVoucher="selectVoucher"
            @selectDiscount="selectDiscount"
            @selectFreight="selectFreight"></order-voucher>
        <!-- 优惠信息 -->
        <ul class="order_deliver_box">
          <span class="info_title" style="display:block;">买家留言</span>
          <div class="order-memo">
            <el-input  type="textarea" class="memo-area" maxlength="300" :rows="5" placeholder="选填:填写内容已和卖家协商确认" v-model="buyerRemark"></el-input>
            <p class="word_num">{{textLen}}/300</p>
          </div>
        </ul>
        <!-- 提交订单 -->
        <div class="submit_order_box">
          <div class="order-text-box">
            <p class="yhlist pad-rt70"><span class="yhtit">商品总金额:</span><span class="yhprice"><em class="font-ora">￥{{allMoney | floatPrices}}</em></span></p>
            <p class="yhlist pad-rt70" v-if="giftAmount > 0"><span class="yhtit">活动优惠:</span><span class="yhprice"><em class="font-ora">-￥{{giftAmount | floatPrices}}</em></span></p>
            <p class="yhlist pad-rt70" v-if="userDiscount !== 1"><span class="yhtit">折扣优惠:</span><span class="yhprice"><em class="font-ora">-￥{{discountPrice | floatPrices}}</em></span></p>
            <p class="yhlist pad-rt70" v-if="voucherCode !== ''"><span class="yhtit">代金券优惠:</span><span class="yhprice"><em >-￥{{voucherValue | floatPrices}}</em></span></p>
            <p class="yhlist pad-rt70" v-if="unlimitedDeductionId !== ''"><span class="yhtit">红包优惠:</span><span class="yhprice"><em >-￥{{discountValue | floatPrices}}</em></span></p>
            <p class="yhlist pad-rt70" v-if="resultDeliver !== ''">
              <span class="yhtit" :class="{'vert_top': oldPostage > 0}">邮费:</span>
              <span class="yhprice">+￥{{postage | floatPrices}}
                <p class="ft-12 color-ora" v-if="oldPostage > 0">运费优惠:{{oldPostage | floatPrices}}</p>
              </span>
            </p>
            <p class="yhlist pad-rt70" v-if="neededInvoice"><span class="yhtit">税费:</span><span class="yhprice">￥{{taxation | floatPrices}}</span></p>
          </div>
          <p class="total_price pad-rt70">
            合计 : <em >{{finalMoney | floatPrices}}</em>元
          </p>
          <el-button type="primary"  class="btn_submit mar-rt70" :disabled="isreadyClick" @click="fetchOrderCreate">提交订单</el-button>
        </div>
      </div>
    </div>
    
    <!-- 发票信息 -->
    <el-dialog title="新增发票" class="dialogorderinfocomfirm" :visible.sync="invovisible"  width="450px" center top="20vh">
      <invoice :modform="modform" @close-dialog="invovisible = false" @get-Invoice="getInvoice"></invoice>
    </el-dialog>

    <!-- 订单中存在缺货的商品 -->
    <el-dialog title="订单失败" class="dialogorderinfocomfirm" :show-close="showclose" :visible.sync="stockVisible" :close-on-click-modal="showclose" width="650px" top="20vh">
      <span>订单中存在部分缺货的商品,下单不成功.请联系客服或删除缺货的商品.</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="backShopcart">返回购物车</el-button>
      </span>
    </el-dialog>
    <!-- 活动弹窗 -->
     <section class="activity-wrapper mask" v-if="showNoticeAct">
      <div class="actvity-notice-pop">
        <div class="activity-over-text">
          <p class="big-tit">活动特价产品不接受退换货</p>
          <p class="small-tit">期盼您购买到合意的商品</p>
        </div>
        <a class="btn-pop-over" @click="overTenThousand(), showNoticeAct = false">确定</a>
        <!-- <router-link :to="{name: 'ActivitySeptExplain'}" class="btn-red-sure">立即查看</router-link> -->
      </div>
    </section>
    <!-- 订单中存在下架的商品-->
    <el-dialog :show-close="showclose" :visible="false" :close-on-click-modal="showclose" width="650px" top="20vh">
      <p class="notice-content">您的订单中含已过期的活动商品,请移除后重新提交订单.</p>
      <span slot="footer" class="txt-center">
        <el-button type="primary" @click="backShopcart">返回购物车</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import {goodsInfoActivity, addressForm, invoice, GiftList, orderVoucher} from '@/components/index'
  import {Select, Option, Checkbox, Button, Dialog, Table, TableColumn, Tooltip, Form, FormItem, Input, Tabs, TabPane, RadioGroup, Radio, InputNumber} from 'element-ui'
  import {setCookie, removeSession, getSession, getCookie} from '@/config/mUntils'
  import {mapState, mapActions} from 'vuex'
  import {getTransport, calculateMoney, postOrderCreate, countTax, checkActivity, getActivityId, voucherActivity, getUsableWarehouseIds} from '@/service/get-data'
  import ReceveInformation from './components/ReceveInfomation.vue'
  import { wareHouseType } from '@/tool'
  export default{
    components: {
      goodsInfo: goodsInfoActivity,
      elSelect: Select,
      elOption: Option,
      elCheckbox: Checkbox,
      elButton: Button,
      elDialog: Dialog,
      elTable: Table,
      elTableColumn: TableColumn,
      elTooltip: Tooltip,
      elForm: Form,
      elFormItem: FormItem,
      elInput: Input,
      elTabs: Tabs,
      elTabPane: TabPane,
      elRadioGroup: RadioGroup,
      elRadio: Radio,
      elInputNumber: InputNumber,
      addressForm,
      invoice,
      GiftList,
      orderVoucher,
      ReceveInformation
    },
    data () {
      return {
        wareHouseType,
        isreadyClick: false,
        selectWarehouseVal: this.warehouseId || 1, // 总仓发货
        voucherStatus: false, // // 送券活动是否在进行,true正在进行,false 未开始或结束
        showclose: false, // 是否显示关闭按钮
        transportlist: [], // 配送方式列表
        resultDeliver: '', // 选中的配送方式
        neededVoucher: false, // 是否勾选兑换码
        voucherValue: 0, // 选中代金券的金额
        discountValue: 0, // 优惠券的值
        unlimitedDeductionId: '', // 优惠券id
        postage: 0, // 运费
        oldPostage: 0, // 运费优惠
        totalWeight: 0, // 总重
        canReach: true, // 快递是否可以到达
        taxation: 0, // 税费
        allMoney: 0, // 商品总金额
        // resultMoney: 0, // 实际支付金额
        taxChecked: true, // 税
        addressId: '', // 页面地址的id
        warehouseId: '', // 分仓id
        productIds: '', // 货品在购物清单中的id数组
        productIdsArr: [],
        neededInvoice: false, // 是否开票
        buyerRemark: '', // 买家留言
        orderId: '', // 订单号
        payResultVisible: false, // 支付结果弹窗
        stockVisible: false, // 订单失败 缺货
        stockList: [], // 缺货商品的列表,
        modform: {}, // 正在修改的表单数据
        invovisible: false, // 发票弹窗
        invoiceForm: {}, // 选中的发票信息
        invoiceId: '',
        orderInfosList: [], // 货品列表
        activityId: 0, // 活动id
        giftAmount: 0, // 优惠总金额
        giftChooseNum: 0, // 可选赠品商品的总共数量
        selectedGiftListParam: '', // 提交订单的赠品列表参数
        giftList: [],
        brandawardArr: '', // 品牌券和代金券的请求参数
        hasAcceptance: this.acceptanceAmount,
        freightDeductionId: '', // 运费抵扣券id
        voucherCode: '',
        nextDiscount: 0,
        nextAmount: 0,
        noticeShow: false,
        ordinaryMoney: 0, // 普通产品的总额
        nowDiscount: 1, // 折扣额度
        discountObj: null,
        level: 0,
        showNoticeAct: false, // 活动提醒弹窗
        hasActive: false,
        activePro: false,
        ordinaryPro: false,
        youRenActivity: false,
        paymode: this.$route.query.paymode || 'actualpayment',
        cityCode: '', // 收货城市的code
        usableWareList: [
          {
            'id': 1,
            'name': '温岭',
            'type': 'MAIN'
          },
          {
            'id': 3,
            'name': '重庆',
            'type': 'MAIN'
          }
        ]
      }
    },
    computed: {
      ...mapState({
        // 全部发票信息
        invoiceList: state => state.invoice.invoiceList,
        // 承兑
        acceptanceAmount: state => state.user.acceptanceAmount,
        // 会员体系
        levelInfoObj: state => state.levelInfoObj,
        userDiscount: state => state.user.discount
      }),
      // 折扣优惠金额
      discountPrice () {
        let discount = 0
        discount = this.allMoney * (1 - this.userDiscount)
        return discount
      },
      // 如果不是最高级 下一个折扣点
      disocuntSpot () {
        return ((1 - this.nextDiscount) * 100).toFixed(1)
      },
      // 减掉优惠金额后的金额
      useDiscountMoney () {
        let totalAmount = 0
        totalAmount = this.allMoney * this.userDiscount
        return totalAmount - this.voucherValue - this.discountValue - this.giftAmount
      },
      selectedIds () {
        let _str = getSession('selecteds')
        return _str
      },
      // 买家留言字数
      textLen () {
        return this.buyerRemark.length
      },
      // 应付金额
      finalMoney () {
        let totalAmount = 0
        totalAmount = this.allMoney * this.userDiscount
        let goodsMoney = totalAmount - this.voucherValue - this.discountValue - this.giftAmount + parseFloat(this.taxation)
        let final = goodsMoney > 0 ? goodsMoney + parseFloat(this.postage) : parseFloat(this.postage)
        return final > 0 ? parseFloat(final).toFixed(2) : 0
      },
      // 红包和代金券是否显示 依据普通的商品总额
      isShowFriAndRed () {
        return this.userDiscount === 1 && this.ordinaryMoney > 0
      },
      // 11月周三 活动的差额提示
      activeNotice () {
        let priceNum
        const noticeObj = {
          1: `单笔订单购满1000元可得500减38优惠券一张，您还差${(1000 - this.useDiscountMoney).toFixed(2)}元 `,
          2: `单笔订单购满2000元可得1000减88优惠券一张，您还差${(2000 - this.useDiscountMoney).toFixed(2)}元`,
          3: '单笔订单购满2000元可得1000减88优惠券一张，多买多得，上不封顶！'
        }
        if (this.useDiscountMoney <= 1000) {
          priceNum = 1
        } else if (this.useDiscountMoney > 1000 && this.useDiscountMoney <= 2000) {
          priceNum = 2
        } else {
          priceNum = 3
        }
        return noticeObj[priceNum]
      },
      warehouseName () {
        return this.usableWareList.filter(item => {
          return item.id === this.selectWarehouseVal
        })
      }
    },
    methods: {
      // 获取分仓ids
      async fetchWarehouseIds () {
        let res = await getUsableWarehouseIds(this.warehouseId)
        if (res.data.resultCode && res.data.resultCode === 2000) {
          this.usableWareList = res.data.data
        }
      },
      // 判断用户是否绑定手机号
      hasMobileFn () {
        let mobile = getCookie('mobile') || this.$store.state.user.mobile
        if (!mobile) {
          this.$store.commit('BINDMOBILE', true)
        }
      },
      // 送券活动
      async fetchVoucherActivity () {
        let res = await voucherActivity()
        this.voucherActList = (res.data.data && res.data.data.voList[0]) || {}
        // 周周活动结束
        if (!('id' in this.voucherActList)) {
          return
        }
        let startTimeParm = this.voucherActList.startTime
        let endTimeParm = this.voucherActList.endTime
        const starTimeStamp = (new Date(startTimeParm.replace(/-/g, '/'))).getTime()
        const endTimeStamp = (new Date(endTimeParm.replace(/-/g, '/'))).getTime()
        let nowTime = (new Date()).getTime()
        // 周周活动开始
        if (nowTime > starTimeStamp && nowTime <= endTimeStamp) {
          this.voucherStatus = true
          return
        }
        // 周周活动还未开始
        if (nowTime < starTimeStamp || nowTime > endTimeStamp) {
          this.voucherStatus = false
        }
      },
      // 获取商品列表 和赠品列表
      async fetchProductGiftList () {
        let res = await checkActivity(this.selectedIds)
        if (res.data.resultCode && res.data.resultCode === 2000) {
          res = res.data
          this.giftAmount = res.data.pmtAmount
          // this.giftList = res.data.ruleResultVOS.length > 0 ? res.data.ruleResultVOS[0]['activityGiftVOS'] : []
          // this.giftChooseNum = res.data.ruleResultVOS.length > 0 ? res.data.ruleResultVOS[0]['num'] : 0
          this.orderInfosList = res.data.productList
          // 假数据
          // const obj = JSON.parse(JSON.stringify(this.orderInfosList[0]))
          // const obj1 = JSON.parse(JSON.stringify(obj))
          // const obj2 = JSON.parse(JSON.stringify(obj))
          // obj.activityId = 39
          // obj.pmtAmount = 20
          // obj1.activityId = 40
          // obj1.pmtAmount = 30
          // obj2.activityId = 1
          // obj2.pmtAmount = 30
          // this.orderInfosList.push(obj)
          // this.orderInfosList.push(obj1)
          // this.orderInfosList.push(obj2)
        } else {
          this.$message.error({
            message: res.data.resultMsg
          })
          this.$router.push({name: 'ShopCart'})
        }
      },
      // 活动id
      async fetchActivityId () {
        let res = await getActivityId()
        if (res.data.resultCode && res.data.resultCode === 2000) {
          this.activityId = res.data.data
          return true
        }
      },
      // 确定选中赠品列表
      getSelectedGiftFun (list) {
        this.selectedGiftListParam = JSON.stringify(list)
      },
      // 获取地址,商品发票信息
      ...mapActions({
        updateCartList: 'fetchCartList',
        getAllInvList: 'getAllInvoice',
        getUserLevelInfo: 'getUserLevelInfo', // 会员等级
        fetchOpenActivity: 'fetchOpenActivity'
      }),
      // 出现缺货商品,返回购物车将其删除
      backShopcart () {
        this.stockVisible = false
        this.$router.push({name: 'ShopCart'})
      },

      // 获取运费模版列表
      async fetchTransport (warehouseId) {
        let res = await getTransport(warehouseId)
        if (res.data.resultCode && res.data.resultCode === 2000) {
          res = res.data
          this.transportlist = res.data
        }
      },
      // 获取邮费
      async fetchPostage () {
        // 地址不能为空
        if (!this.addressId) {
          this.$message({
            message: '请先填写收货地址',
            type: 'error'
          })
          return false
        }
        //  TODO:过期商品优化
        let res = await calculateMoney(this.resultDeliver, this.productIds, this.addressId, this.levelInfoObj.freightReduction, this.freightDeductionId)
        if (res.data.resultCode && res.data.resultCode === 2000) {
          res = res.data
          this.postage = (res.data.money).toFixed(2)
          this.oldPostage = (res.data.pmtAmount).toFixed(2)
          this.canReach = res.data.canReach
        } else {
          this.$message({
            message: '您添加的活动商品已过期'
          })
        }
      },

      // 税费
      async calcTax () {
        if (this.neededInvoice) {
          let totalAmount = 0
          totalAmount = this.allMoney * this.userDiscount
          let calMoney = totalAmount - this.voucherValue - this.discountValue - this.giftAmount
          calMoney = calMoney >= 0 ? calMoney : 0
          let res = await countTax(calMoney)
          if (res.data.resultCode && res.data.resultCode === 2000) {
            this.taxation = res.data.data
          }
        } return false
      },
      // 发票下拉框
      selectInvo (item) {
        let list
        this.invoiceList.map((item, index) => {
          if (item.id === this.invoiceId) {
            list = item
          }
        })
        this.invoiceForm = list
      },
      // 打开发票弹窗
      openNewInvo () {
        this.modform = {}
        this.invovisible = true
      },
      getInvoice (form, id) {
        this.invoiceForm = form
        this.invoiceForm['id'] = id
        this.invoiceId = id
      },
      // 缺货商品弹窗
      showStockBox () {
        let [stockLen, html] = [this.stockList.length, '']
        this.stockList.map((item, index) => {
          html += item.goodsName + ' - ' + item.productName + ', '
        })
        const h = this.$createElement
        const _this = this
        this.$msgbox({
          title: '确认',
          message: h('p', null, [
            h('h2', null, `${stockLen}类商品缺货`),
            h('span', null, `分别是${html}`),
            h('i', { style: 'color: #ea1e1e' }, '请移除缺货的商品后在下单')
          ]),
          confirmButtonText: '确定',
          beforeClose: (action, instance, done) => {
            _this.$router.push({name: 'ShopCart'})
            done()
          }
        })
      },
      /**
       * ====================================
       * 提交订单
       * ====================================
       */
      // 判断金额数目 大于 5万
      isShowActivityPop () {
        if (this.activePro) {
          this.showNoticeAct = true
        } else {
          this.overTenThousand()
        }
      },
      // 金额是否超过上线10000
      overTenThousand () {
        if (Number(this.finalMoney) > 50000) {
          this.$confirm('<p>您的订单总金额超过5万元，仅支持<span class="color-red">线下支付或承兑支付</span>是否继续支付</p>', '', {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '继续支付',
            cancelButtonText: '取消支付',
            type: 'warning'
          }).then(() => {
            this.createOrderId(true)
          }).catch(() => {
            console.log(`取消线下支付`)
          })
        } else {
          this.createOrderId()
          // this.$router.push({name: 'Cashier', query: {openInvoice: this.neededInvoice, rid: '124567894548', isLimit: false}})
        }
      },
      // 提交订单
      fetchOrderCreate () {
        // 订单列表是否含有缺货商品
        if (this.stockList.length && this.stockList.length > 0) {
          this.showStockBox()
          return false
        }
        // 地址不能为空
        if (!this.addressId) {
          this.$message({
            message: '请先填写收货地址',
            type: 'error'
          })
          return false
        }
        // 收件地址能否送达
        if (!this.canReach) {
          this.$message({
            message: '收货地区不在配送范围内',
            type: 'error'
          })
          return false
        }
        // 判断配送方式是否为空
        if (this.resultDeliver === '') {
          this.$message({
            message: '请选择配送方式',
            type: 'error'
          })
          return false
        }
        // 勾选代金券兑换码
        if (this.neededVoucher && !this.voucherCode) {
          this.$message({
            message: '请输入代金券兑换码',
            type: 'error'
          })
          return false
        }
        // 开发票
        if (this.neededInvoice && JSON.stringify(this.invoiceForm) === '{}') {
          this.$message({
            message: '请选择发票信息',
            type: 'error'
          })
          return false
        }
        // 判断金额数目 大于 5万
        this.isShowActivityPop()
      },
      // 生成订单号
      async createOrderId (limit = false) {
        this.isreadyClick = true
        let res = await postOrderCreate(
          this.addressId,
          this.selectWarehouseVal,
          this.buyerRemark,
          this.neededInvoice,
          this.invoiceForm.title,
          this.invoiceForm.eleCode,
          this.productIds,
          this.resultDeliver,
          this.voucherCode,
          this.selectedGiftListParam,
          this.unlimitedDeductionId,
          this.freightDeductionId,
          0,
          this.paymode === 'advancepayment')
        if (res.data.resultCode && res.data.resultCode === 2000) {
          removeSession('selectedProList') // 单号生成成功时, 清除本地 选择货品列表的数据
          res = res.data
          let resorder = res.data.split(',')[0]
          this.orderId = resorder
          setCookie('orderId', res.data)
          this.updateCartList() // 更新购物车
          let totalPrice = this.finalMoney
          this.isreadyClick = false
          // 付款金额为0
          if (!parseFloat(this.finalMoney)) {
            this.$router.replace({name: 'Paystatus', query: {payStatus: '1', orderId: res.data}})
            return true
          }
          this.$router.replace({name: 'Cashier', query: {openInvoice: this.neededInvoice, rid: this.orderId, isLimit: limit, totalPrice: totalPrice}})
          return true
        } else if (res.data.resultMsg === '有缺货的商品') {
          this.isreadyClick = false
          this.stockVisible = true
          return false
        } else {
          this.isreadyClick = false
          this.$message({
            message: res.data.resultMsg,
            type: 'error'
          })
          return false
        }
      },
      // ===============3种优惠券的选择===============
      selectVoucher (obj, needvoucher, deductionNum) {
        this.neededVoucher = needvoucher
        let voucherObj = obj
        let deductionNumber = deductionNum
        if (voucherObj.id) {
          this.voucherValue = voucherObj.amount
          this.voucherCode = voucherObj.id
        } else {
          this.voucherCode = ''
          this.voucherValue = 0
        }
        if (this.neededInvoice) {
          this.calcTax()
        }
        if (needvoucher) { this.voucherCode = deductionNumber }
      },
      selectDiscount (obj) {
        let discountObj = obj
        if (obj.id) {
          this.unlimitedDeductionId = discountObj.id
          this.discountValue = discountObj.amount
        } else {
          this.unlimitedDeductionId = ''
          this.discountValue = 0
        }
        if (this.neededInvoice) {
          this.calcTax()
        }
      },
      selectFreight (obj) {
        if (!obj.length) {
          this.freightDeductionId = ''
          if (this.resultDeliver) {
            this.fetchPostage()
          }
          return
        }
        this.freightDeductionId = obj[0]['id']
        if (this.resultDeliver) {
          this.fetchPostage()
        }
        if (this.neededInvoice) {
          this.calcTax()
        }
      },

      // ==============获取地址id==============
      getAddrId (id) {
        this.addressId = id
      },
      getWareId (id) {
        this.warehouseId = id
      },
      // 收货地址变动
      modifReceiveAddr (warehouseId, needRequestWare = true) {
        this.warehouseId = warehouseId
        this.selectWarehouseVal = warehouseId
        // let reswarehouseId = this.selectWarehouseVal ? 1 : warehouseId
        if (needRequestWare) {
          this.fetchWarehouseIds()
        }
        // 分仓列表
        this.fetchTransport(warehouseId) // 配送方式列表重新获取
        this.resultDeliver = '' // 取消配送
      }
    },

    mounted () {
      this.hasMobileFn()
      // this.fetchActivityId()
      // this.fetchVoucherActivity()
      this.fetchProductGiftList() // 获取赠品列表 下单货品列表
      this.fetchTransport() // 获取配送列表
      this.getAllInvList() // 获取所有发票的列表
      this.getUserLevelInfo()
    },
    watch: {
      buyerRemark (newval, oldval) {
        if (newval.length >= 300) {
          if (oldval !== 300) {
            this.$message({
              message: '字数最多100个',
              type: 'danger'
            })
          }
          this.buyerRemark = this.buyerRemark.substring(0, 300)
        }
      },
      orderInfosList (newVal) {
        let _arr = []
        let brandawardArr = []
        let brandObj = {}
        let weight = 0
        let money = 0 // 总价格
        let ordinaryMoney = 0 // 普通商品的金额
        newVal.map((item, index) => {
          weight += parseFloat(item.weight * item.number)
          money += item.number * item.productPrice // 商品总金额 - item.pmtAmount
          _arr.push(item.id)
          this.productIdsArr = _arr
          if (item.inventoryStatus === 3) {
            this.stockList.push(item)
          }
          // 普通产品
          if (!item.activity) {
            this.ordinaryPro = true
            ordinaryMoney += parseFloat(item.productPrice * item.number)
            this.ordinaryMoney = ordinaryMoney.toFixed(2) - 0
            // 品牌券请求id
            brandObj.id = item.productId
            brandObj.num = item.number
            brandawardArr.push({...brandObj})
          }
          if (item.activity) {
            this.activePro = true
          }
        })
        this.brandawardArr = JSON.stringify(brandawardArr)
        _arr = JSON.stringify(_arr)
        let len = _arr.length
        this.productIds = _arr.substring(1, len - 1)
        this.allMoney = money.toFixed(2)
        // TODO: 保留4位小数
        this.totalWeight = weight.toFixed(4)
      },
      neededInvoice (newval) {
        if (newval) {
          this.calcTax()
        } else {
          this.taxation = 0
        }
      },
      // 代金券金额
      voucherValue (newval) {
        this.calcTax()
      },
      // 优惠券金额
      discountValue (newVal) {
        this.calcTax()
      },
      // 更换配送方式
      resultDeliver (newVal) {
        if (!newVal) { // 地址重新选择后,resultDeliver为''
          this.postage = 0
          this.oldPostage = 0
          this.canReach = true
          this.freightDeductionId = ''
        }
      },
      // 是否先择总仓发货
      selectWarehouseVal (newVal) {
        this.modifReceiveAddr(newVal, false)
      }
    }
  }
</script>
<style lang="scss" scoped>
  .order-submit-box {
    margin-bottom: 30px;
  }
  .warenotice{
    font-size: 13px;
    line-height: 2;
  }
  .orderInfoBox{
    position: relative;
    margin:30px 0;
    padding: 0 50px 0 40px;
    background: #ffffff;
    overflow: hidden;
  }
  .font-ora{
    @include fontbase(#F55923, 16px, 1.5);
  }
  .info_title{
    display:inline-block;
    color: #333333;
    font-size: 18px;
    line-height: 25px;
    margin-bottom: 12px;

  }
  .addr_info_tit{
    width: 64px;
    display: inline-block;
  }
  .pdt6{padding-top: 6px;}
  .pad-right8{padding-right: 8px;}
  .border_bt{
    @include border_bt();
  }
  .order-invoice {
    position: relative;
    font-size: 14px;
    color: #666666;
    padding-bottom: 20px;
     @include border_bt();
  }

  .invoice_box{
    margin-top: 18px;
    .invoice_input{
      display: inline-block;
    }
  }
  .order_detail >li{
    line-height: 22px;
    color: #666666;
    margin-bottom:7px;
    &:last-child{
      margin-bottom:0;
    }
  }
  .order_deliver_box{
    position: relative;
    padding: 38px 0;
    color:#666666;
    overflow: hidden;
    @include border_bt();
    .order_font{
      color: RGBA(102, 102, 102, 1);
      font-size: 16px;
      line-height: 22px;
    }
    .order-text-box{
      float: right;
      margin-bottom: 10px;
    }
    .info_title_rt{
      float: right;
      line-height: 24px;
    }
  }
  .youren_text{
    color: #2A91D2;
    cursor: pointer;
  }
  .reward{
    font-size: 12px;
    background: #ff0000;
    padding: 4px;
    color: #fff;
    border-radius: 2px;
  }
  .yhtit{
      font-size: 14px;   
      display: inline-block;
      width: 180px;
      margin-right: 20px;
      text-align: right;
    }
    .yhprice{
      font-size: 14px;
      display: inline-block;
      color: #5f5f5f;
      width: 100px;
      text-align: right;
      font-family: verdana;
    }
  .submit_order_box{
    float: right;
    .order-text-box{
      margin-bottom: 15px;
      .yhlist{
        // height: 40px;
        // line-height: 40px;
        // clear: both;
        // float: right;
        // padding-right: 70px;
        margin-bottom: 7px;
      }
    }
    
  }
  .order-memo{
    display: inline-block;
    margin: 12px 0;
    .word_num{
      font-size: 14px;
      text-align: right;
      line-height: 15px;
      margin-top: 5px;
    }
    .memo-area{
      font-family: 'microsoft yahei';
      width: 250px;
      margin-top: -16px;
    }
  }
  .item .el-tooltip__popper {
      padding: 8px 10px;
    }
  .order_deliver_title{
    font-size: 16px;
    width: 80px;
    display: inline-block;
  }
  .money_text{
    float:right;
    padding-right:70px;
    line-height:40px;
  }
  .order_deliver_content{
    padding-left: 10px;
  }
  .order_select{
    padding-right: 24px;
    padding-left: 8px;
  }
  .btn_voucher{
    color: #333333;
    background: #ffcc00;
    border-radius: 2px;
    height: 40px;
    line-height: 40px;
    display: inline-block;
    padding: 0 25px;
  }
  .input_voucher{
    width:203px;
    padding-right: 20px;
    padding-left: 8px;
  }
  .notice_text{
    cursor: pointer;
    font-size: 14px;
    color: #2A91D2;
  }
  .youren-special-box{
    float: left;
    margin-top: 3px;
    line-height: 1.5;
    .title{
      color: #ff0000;
      font-size: 13px;
    }
    .info{
      color: #999;
      line-height: 1.5;
      font-size: 12px
    }
  }
  .submit_order_box{
    text-align: right;
    padding-top: 27px;
    padding-bottom:85px;
    line-height: 1.8;
    .total_price{
      font-size:16px;
      color: #666666;
      line-height: 33px;
      margin-bottom: 12px;
      em{
        font-style: normal;
        font-weight:500;
        font-size: 36px;
        color: #F55923;
      }
    }
    .btn_submit{
      width: 300px;
      height: 60px;
      font-size: 16px;
      color: #333333;
    }
  }
  .blue_font{
    font-size: 14px;
    color: #2A91D2;
  }

  .formbox{
    width: 400px;
    margin-top: 20px;
  }

  .orderpay-box{
    position: relative;
    margin-bottom: 50px;
    margin-top: 20px;
  }
  .order_border{
    border: 1px #dedede solid;
    margin-top: 15px;
    font-size: 16px;
    color: #333;
    height: 45px;
    line-height: 45px;
    padding: 0 15px;
  }
  .pay-title{
    background: #f7f7f7;
    padding-left: 15px;
    font-size: 14px;
    line-height: 40px;
    color: #666;
    margin-bottom: 15px;
  }
  .pay-p{
    line-height: 30px;
  }
  .order_radio{
    margin-top: 15px;
    font-size: 16px;
    color: #333;
    height: 45px;
    line-height: 45px;
    margin-bottom: 15px;
  }
  .iconfont{
    font-size: 28px;
    color: #ffcc00;
    vertical-align: middle;
  }
  .price{
    color:#F55923;
  }
  .radio-box{
    .radio-label{
      padding-left: 12px;
      border: 1px solid #dedede;
      border-radius: 2px;
      height: 45px;
      line-height: 45px;
    }
    .radio-text{
      padding-right: 27px;
      font-size: 16px;
      font-weight: 600;
      color: #ffcc00;
      letter-spacing: 0.05em;
    }
  }
  .radio-img{
    height: 35px;
    vertical-align: middle;
  }
  .pay-btn-box{
    display: block;
    text-align: right;
    overflow: hidden;
    margin-top: 20px;
  }
  .bank-box{
    font-size: 14px;
    line-height: 25px;
    margin-top: 30px;
    color: #666;
    .title{
      // width: 58px;
      text-align: left;
      font-size: 14px;
      display: inline-block;
      padding-left: 15px;
    }
  }
  .order-notice-box{
    height:62px;
    background:rgba(255,245,206,1);
    box-shadow:0px 2px 1px 0px rgba(0,0,0,0.05);
    font-size:16px;
    line-height: 62px;
    color: #333333;
  }
  .fixed-notice{
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 5;
  }
  .activity-over-text{
    .big-tit{
      font-size: 18px;
      color:rgba(48,48,48,1);
      line-height:25px;
      margin-bottom: 25px;
    }
    .small-tit{
      font-size:14px;
      color:rgba(107,107,107,1);
      line-height:20px;
      margin-bottom: 40px;
    }
    
  }
  .yourentext{
    height: 430px;
    font-size: 14px;
    overflow-y: scroll;
    text-align: left;
  }
  .btn-pop-over{
    display: inline-block;
    width:200px;
    height:50px;
    background:rgba(255,225,0,1);
    border-radius:5px;
    font-size:16px;
    color:rgba(48,48,48,1);
    line-height: 50px;
    text-align: center;
  }
  .notice-content{
    padding: 27px 30px;
    text-align: center;
    font-size: 18px;
  }
  .agreement-box{
    margin-top: 20px;
  }
</style>
<style lang="scss">
.el-tabs__item {
  font-size:16px;
}
.dialogorderinfocomfirm {
  .el-dialog__header{
    background: #f7f7f7;
    padding-top: 15px!important;
  }
}



.el-dialog--center .el-dialog__body {
    text-align: initial;
    padding: 30px 27px 20px;
  }
</style>

